package com.itcast.activiti.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.itcast.activiti.domain.TaskStart;
import com.itcast.activiti.event.NotifyTaskApplyEvent;
import com.itcast.activiti.service.IHistoryService;
import com.itcast.activiti.service.ITaskRuntimeService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.BaseExecutionListener;
import org.activiti.engine.task.Task;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 审批结果通知
 */
@Slf4j
@Component
public class NotifyTaskApplyListener {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ITaskRuntimeService iTaskRuntimeService;
    @Autowired
    private IHistoryService iHistoryService;

    @Value("${activiti.rocketmq.topic.activiti}")
    private String topic;


    @EventListener
    public void execute(NotifyTaskApplyEvent event) {
        JSONObject jsonObject = new JSONObject();
        String businessKey = event.getBusinessKey();
        jsonObject.put("businessKey", businessKey);
        jsonObject.put("taskId", event.getTaskId());
        jsonObject.put("assignee", event.getAssignee());
        TaskStart taskStart = event.getTaskStart();
        // 自动审批 逻辑处理 autoNextComplete 为true时不发送消息，会在节点审批不是同一个人发送一个autoNextComplete不为true的事件
        if (Boolean.TRUE.equals(taskStart.getAutoNextComplete())) {
            log.info("自动审批不发送mq消息");
            return;
        }
        jsonObject.put("passbackParam", taskStart.getPassbackParam());
        jsonObject.put("taskRequestParam", taskStart);
        if (StringUtils.hasText(taskStart.getEvent())) {
            jsonObject.put("event", taskStart.getEvent());
        } else {
            List<Task> tasks = iTaskRuntimeService.listTask(event.getTenantId(), event.getBusinessKey(), null);
            if (tasks == null || tasks.size() == 0) {
                jsonObject.put("event", BaseExecutionListener.EVENTNAME_END);
            } else {
                jsonObject.put("event", BaseExecutionListener.EVENTNAME_TAKE);
            }
        }
        // 获取下一个任务
        Map<String, Object> map = iHistoryService.getNextTask(businessKey, event.getTenantId(), event.getTaskId());
        jsonObject.put("nextTask", map);
        log.info("NotifyTaskApplyListener {}", jsonObject);
        rocketMQTemplate.convertAndSend(String.format("%s:%s", topic, "TAG_TASK_APPROVE"), jsonObject);
    }
}
